﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

namespace RQX.Common.Web.Web.Swagger
{
    public static class SwaggerServiceExtension
    {
        public static void AddSwaggerService(this IServiceCollection services)
        {
            services.AddSwaggerGen(swagger =>
            {
                swagger.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "Apollo API Doc",
                    Version = "v1",
                    Description = "四川卫宁 手术麻醉系统API文档"
                });
                swagger.CustomSchemaIds(k => k.FullName);
                swagger.DocInclusionPredicate((docName, description) => true);
                //添加xml文件
                var xmlFiles = Directory.GetFiles(AppContext.BaseDirectory, "*.xml", SearchOption.AllDirectories);
                foreach (var xmlfilePath in xmlFiles)
                {
                    swagger.IncludeXmlComments(xmlfilePath, true);
                }
                //swagger的Tag排序
                swagger.DocumentFilter<SwaggerDocTagOrder>();
                //swagger登录授权
                swagger.AddSecurityDefinition("登录Token填写", new OpenApiSecurityScheme()
                {
                    Description = "在下框中输入请求头中需要添加Jwt授权Token,请调用​/api​/Base​/BsUser​/DoLogin接口获取,管理员账号密码admin，普通权限账号密码user",
                    Name = "token",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme,
                                Id = "登录Token填写"
                            }
                        },
                        new string[] { }
                    }
                });
            });
        }

        public static void UseSwaggerConfigure(this IApplicationBuilder app)
        {
            //app.UseStaticFiles();
            //启用中间件服务生成Swagger作为JSON终结点
            app.UseSwagger();
            //启用中间件服务对swagger-ui，指定Swagger JSON终结点
            //UseSwaggerUi3WithApiExplorer更流畅
            app.UseSwaggerUI(swagger =>
            {
                swagger.SwaggerEndpoint("./swagger/v1/swagger.json", "Apollo API V1");
                swagger.RoutePrefix = string.Empty;
                swagger.DocumentTitle = "手麻系统API接口文档";
                swagger.DocExpansion(DocExpansion.List);
                swagger.DefaultModelsExpandDepth(-1);
                //swagger.InjectJavascript("RQX.Common.Web.Web.Swagger.SwaggerExtension.js");
            });
        }

    }
}
